package com.chinaer.util;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;

public class DateUtil {
	private static Calendar calendar;
	private static Date date;
	static {
		calendar = Calendar.getInstance(TimeZone.getTimeZone("GMT+8:00"));
		date = new Date();
	}

	private static void setTime(long time) {
		date.setTime(time);
		calendar.setTime(date);
	}

	private static String formatTimeInteger(int n) {
		if (n < 10)
			return "0" + n;
		else
			return String.valueOf(n);
	}

	private static String formatYearInteger(int n) {
		if (n < 10)
			return "000" + n;
		else if (n < 100)
			return "00" + n;
		else if (n < 1000)
			return "0" + n;
		else
			return String.valueOf(n);
	}

	private static String toString(long time, boolean hasDelimitors,
			boolean hasTime,boolean hasMillisecond) {
		setTime(time);
		StringBuffer s = new StringBuffer();
		s.append(formatYearInteger(calendar.get(Calendar.YEAR))).append(
				hasDelimitors ? "-" : "");
		s.append(formatTimeInteger(calendar.get(Calendar.MONTH) + 1)).append(
				hasDelimitors ? "-" : "");
		s.append(formatTimeInteger(calendar.get(Calendar.DAY_OF_MONTH)))
				.append(hasDelimitors && hasTime ? " " : "");
		if (hasTime) {
			s.append(formatTimeInteger(calendar.get(Calendar.HOUR_OF_DAY)))
					.append(hasDelimitors ? ":" : "");
			s.append(formatTimeInteger(calendar.get(Calendar.MINUTE))).append(
					hasDelimitors ? ":" : "");
			s.append(formatTimeInteger(calendar.get(Calendar.SECOND)));
		}
		if(hasMillisecond){
			s.append(formatTimeInteger(calendar.get(Calendar.MILLISECOND)));
		}
		return s.toString();
	}
	public static String getCurrentDate(long time) {
		return toString(time, false, false,false);
	}
	public static String getCurrentDate() {
		return toString(new Date().getTime(), false, true,true);
	}
	
	public static long stringToDate(String str) {
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date date = null;
		try {
			date = format.parse(str);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		
		return date.getTime();
	}
	
	public static void main(String[] args) {
//		DateUtil util = new DateUtil();
		System.out.println(DateUtil.getCurrentDate());
	}

}
